package com.liang.kit;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public final class TypeConverter {
	
	private static final int timeStampLen = "2011-01-18 16:18:18".length();
	private static final String timeStampPattern = "yyyy-MM-dd HH:mm:ss";
	private static final String datePattern = "yyyy-MM-dd";

	public static final Object convert(Class<?> clazz, Object value) throws ParseException {
		Object result = value;
		if (clazz == Integer.class || clazz == Integer.TYPE) {
			result = Integer.parseInt(value.toString());
		}else if (clazz == Long.class || clazz == Long.TYPE) {
			result = Long.parseLong(value.toString());
		}else if (clazz == java.util.Date.class) {
			if(value instanceof String){
				result=value.toString().length() >= timeStampLen?new SimpleDateFormat(timeStampPattern).parse(value.toString()): new SimpleDateFormat(datePattern).parse(value.toString());
			}
        } else if (clazz == java.sql.Date.class) {
			if(value instanceof String){
				 result = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value.toString()).getTime());
			}
        }else if (clazz == java.sql.Time.class) {
        	result = java.sql.Time.valueOf(value.toString());
		}else if (clazz == java.sql.Timestamp.class) {
        	result = java.sql.Timestamp.valueOf(value.toString());
		}else if (clazz == Double.class||Double.TYPE==clazz) {
        	result = Double.parseDouble(value.toString());
		}else if (clazz == Float.class||Float.TYPE==clazz) {
        	result = Float.parseFloat(value.toString());
		}else if (clazz == Boolean.class) {
        	result = Boolean.parseBoolean(value.toString()) || "1".equals(value);
		}else if (clazz == java.math.BigDecimal.class) {
        	result = new java.math.BigDecimal(value.toString());
		}else if (clazz == java.math.BigInteger.class) {
			result = new java.math.BigInteger(value.toString());
		}else if (clazz == byte[].class) {
			result = value.toString().getBytes();
		}else if (Character.TYPE == clazz) {
			if ((value != null) && (value.toString().length() > 0)) {
				result=Character.valueOf(value.toString().charAt(0));
			}
		} else if ((Short.TYPE == clazz)|| (Short.class == clazz)) {
			result= Short.valueOf(value.toString());
		}else if (String.class == clazz) {
			result= String.valueOf(value);
		} 
		return result;
	}
}

